export const request = (opt) => {
	return new Promise((resolve, reject) => {
		let token = wx.getStorageSync("token");
		const header = {
			'Content-Type': 'application/json',
			Authorization: `Bearer ${token}`
		}
		wx.request({
			url: opt.url,
			header: header,
			method: opt.method,
			data: opt.data,
			success(res) {
        if(res.statusCode == "417"){
          console.log("success res: 鉴权失败，请重新登录")
          wxRefreshToken()
					reject("鉴权失败，请重新登录")
        }
				if (res.data.code == "200"){
				console.log("<===request success===>:",opt.url)
					resolve(res.data);	
				}else{
				console.log("<===request failure===>:",opt.url)
				console.log(res.data)
					reject(res.data);
				}
			},
			fail(res){
				console.log("<===request failure statue===>:",opt.url);
				console.log(res);
				if(res.statusCode == "417"){
          console.log("fail res: 鉴权失败，请重新登录")
          wxRefreshToken()
				}
				reject(res);
			}
		})
		
	})
}

export const wxRefreshToken = () => {
	wx.login({
		success(res) {
			//{errMsg: "login:ok", code: "0c1gZp0w3rIRJ23W920w3PTH4p0gZp0L"}
			console.log("refersh token wxLogin success")
			console.log(res)
			var opt = {
        url: "http://localhost:8700" + "/auth/wx/login",
				method: "post",
				data: res.code,
			}
			wx.request({
				url: opt.url,
				method: opt.method,
				data: opt.data,
				success(res){
					console.log("refresh success ", res)
					wx.setStorageSync("token", res.data.data.token);
				},
				fail(res){
					console.log("refresh success ", res)
					wx.setStorageSync("token",res.data.data.token);
				}
			})
		},
		fail(res){
			console.log("refersh token wxLogin error")
			console.log(res)
		}
	})
	
}
